package com.alinesno.cloud.common.web.basic.auth.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.alinesno.cloud.common.facade.pageable.DatatablesPageBean;
import com.alinesno.cloud.common.facade.response.ResponseBean;
import com.alinesno.cloud.common.facade.response.ResponseGenerator;
import com.alinesno.cloud.common.facade.wrapper.RestWrapper;
import com.alinesno.cloud.common.web.basic.auth.entity.BasicResourceEntity;
import com.alinesno.cloud.common.web.basic.auth.repository.BasicResourceRepository;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;

/**
 * 菜单控制层
 * @author WeiXiaoJin
 * @since 2019年12月12日 上午8:20:23
 */
@Controller
@RequestMapping("basic/menus")
public class MenusController {

	private static final Logger log = LoggerFactory.getLogger(MenusController.class) ; 

	@Autowired
	private BasicResourceRepository feign ; 

	@ResponseBody
	@GetMapping("list")
    public Object allMenus(){
		List<BasicResourceEntity> list = feign.findAll() ; 
		return list ; 
    }

	@ResponseBody
	@PostMapping("/datatables")
    public DatatablesPageBean datatables(HttpServletRequest request , Model model ,  DatatablesPageBean page){
		log.debug("page = {}" , ToStringBuilder.reflectionToString(page));
		return this.toPage(model, feign , page, request) ;
    }
	
	/**
	 * 菜单管理查询功能  
	 * @return
	 */
	@GetMapping("/add")
    public void add(Model model , HttpServletRequest request){
    }
	
	
	/**
	 * 保存新对象 
	 * @param model
	 * @param ManagerCodeEntity
	 * @return
	 */
	@ResponseBody
	@PostMapping("/save")
	public ResponseBean save(Model model , HttpServletRequest request, BasicResourceEntity dto) {
		log.debug("===> save dto:{}" , ToStringBuilder.reflectionToString(dto));
		dto = feign.save(dto) ; 
		return ResponseGenerator.ok(null) ; 	
	}
	
	
	/**
	 * 删除
	 */
//	@AccountRecord(type=RecordType.OPERATE_DELETE)
//	@ResponseBody
//	@GetMapping("/delete")
//    public ResponseBean delete(@RequestParam(value = "rowsId[]") String[] rowsId){
//		log.debug("rowsId = {}" , ToStringBuilder.reflectionToString(rowsId));
//		if(rowsId != null && rowsId.length > 0) {
//			feign.deleteByIds(rowsId); 
//		}
//		return ResponseGenerator.ok(null) ; 
//    }
	
	/**
	 * 删除
	 */
	@ResponseBody
	@GetMapping("/delete")
    public ResponseBean delete(String ids){
		log.debug("delete ids:{}" , ids);
		
		String[] rowsId = ids.split(",") ; 
		if (rowsId != null && rowsId.length > 0) {
			for(String id : rowsId) {
				feign.deleteById(id);
			}
		}
		return ResponseGenerator.ok(null);
    }
	
	/**
	 * 删除
	 */
//	@AccountRecord(type=RecordType.OPERATE_DELETE)
//	@ResponseBody
//	@GetMapping("/delete")
//    public ResponseBean delete(String id){
//		return this.delete(new String[] {id}) ; 
//    }
	
	/**
	 * 详情
	 * @return
	 */
	
	@GetMapping("/detail")
    public void detail(HttpServletRequest request ,Model model , String id){
		Assert.hasLength(id , "主键不能为空.");
		BasicResourceEntity code = feign.getOne(id) ; 
		model.addAttribute("bean", code) ; 
    }
	
	
	/**
	 * 修改功能  
	 * @return
	 */
	
	@GetMapping("/modify")
    public void modify(HttpServletRequest request ,Model model , String id){
		Assert.hasLength(id , "主键不能为空.");
		BasicResourceEntity code = feign.getOne(id) ; 
		model.addAttribute("bean", code) ; 
    }
	

	/**
	 * 详情
	 */
	@ResponseBody
	@GetMapping("/detailJson")
    public ResponseBean detailJson(String id){
		log.debug("id = {}" , id);
		BasicResourceEntity bean = feign.findById(id).get() ; //.findEntityById(id) ; 
		return bean != null?ResponseGenerator.ok(bean):ResponseGenerator.fail("") ; 
    }

	/**
	 * 保存
	 * @param model
	 * @param request
	 * @param ManagerApplicationEntity
	 * @return
	 */
	@ResponseBody
	@PostMapping("/update")
	public ResponseBean update(Model model , HttpServletRequest request, BasicResourceEntity dto) {
		
		if(dto != null && StringUtils.isNotBlank(dto.getId())) {
			
			BasicResourceEntity oldBean = feign.getOne(dto.getId()) ; 
			BeanUtil.copyProperties(dto, oldBean ,CopyOptions.create().setIgnoreNullValue(true));
			
			oldBean = feign.save(oldBean) ; 
			return ResponseGenerator.ok(null) ; 	
			
		}else {
			return this.save(model, request, dto) ; 
		}
	}

	/**
	 * 查询所有
	 * @param applicationId
	 * @return
	 */
	@ResponseBody
	@GetMapping("findAll")
	public List<BasicResourceEntity> findAll(){
		return feign.findAll() ; 
	}

	/**
	 * 查询返回实体
	 * @param applicationId
	 * @return
	 */
	@ResponseBody
	@GetMapping("getOne")
	public BasicResourceEntity getOne(@RequestParam("id") String id) {
		return feign.getOne(id) ; 
	}

	/**
	 * 查询统计 
	 * @param applicationId
	 * @return
	 */
	@ResponseBody
	@GetMapping("count")
	public long count() {
		return feign.count() ; 
	}
	
	/**
	 * 删除
	 * @param id
	 */
	@ResponseBody
	@GetMapping("deleteById")
	public void deleteById(@RequestParam("id") String id) {
		feign.deleteById(id); ; 
	}

	/**
	 * 查询所有通过applicationId
	 * @param applicationId
	 * @return
	 */
	@ResponseBody
	@GetMapping("findAllByApplicationId")
	List<BasicResourceEntity> findAllByApplicationId(@RequestParam("applicationId") String applicationId){
		return feign.findAllByTenantId(applicationId) ; 
	}
	
	/**
	 * 查询所有通过applicationId
	 * @param applicationId
	 * @return
	 */
	@ResponseBody
	@GetMapping("findAllByTenantId")
	List<BasicResourceEntity> findAllByTenantId(@RequestParam("tenantId") String tenantId){
		return feign.findAllByTenantId(tenantId) ; 
	}

	
	@SuppressWarnings("unchecked")
	protected DatatablesPageBean toPage(Model model, BasicResourceRepository feign, DatatablesPageBean page , HttpServletRequest request) {
		
//		RestWrapper restWrapper = new RestWrapper() ; 
//		restWrapper.setPageNumber(page.getStart());
//		restWrapper.setPageSize(page.getLength());
//		
//		log.debug("===> DatatablesPageBean:{}" , JSONObject.toJSON(page));
//		
//		restWrapper.builderCondition(page.getCondition()) ; 
//		
//		Page<BasicResourceEntity> pageableResult = feign.findAll(page.buildFilter(null, request) , PageRequest.of(page.getStart()/page.getLength(), page.getLength())) ; 
//		
//		DatatablesPageBean p = new DatatablesPageBean();
//		p.setData(pageableResult.getContent());
//		p.setDraw(page.getDraw());
//		p.setRecordsFiltered((int) pageableResult.getTotalElements());
//		p.setRecordsTotal((int) pageableResult.getTotalElements());
//		
//		return p ;
		
		// ----------------------- 兼容bootstrap table_start ---------------
		if(page.isBootstrapTable()) {
			page.setStart(page.getPageNum()-1);
			page.setLength(page.getPageSize());
		}
		// ----------------------- 兼容bootstrap table_end ---------------
		
		RestWrapper restWrapper = page.getRestWrapper() ; // new RestWrapper() ; 
		restWrapper.setPageNumber(page.getStart());
		restWrapper.setPageSize(page.getLength());
		
		log.debug("===> DatatablesPageBean:{}" , JSONObject.toJSON(page));
		
		restWrapper.builderCondition(page.getCondition()) ; 
		
		Page<BasicResourceEntity> pageableResult = null ; 
		if(page.isBootstrapTable()) {
			pageableResult = feign.findAll(page.buildFilter(null, request) , PageRequest.of(page.getStart(), page.getLength())) ; 
		}else {
			pageableResult = feign.findAll(page.buildFilter(null, request) , PageRequest.of(page.getStart()/page.getLength(), page.getLength())) ; 
		}
		
		// DatatablesPageBean p = new DatatablesPageBean();
		
		if(page.isBootstrapTable()) {
			// ----------------------- 兼容bootstrap table_start ---------------
			page.setRows(pageableResult.getContent());
			page.setTotal((int) pageableResult.getTotalElements());
			page.setCode(HttpStatus.OK.value()); 
			// ----------------------- 兼容bootstrap table_end ---------------
		} else {
			page.setData(pageableResult.getContent());
			page.setDraw(page.getDraw());
			page.setRecordsFiltered((int) pageableResult.getTotalElements());
			page.setRecordsTotal((int) pageableResult.getTotalElements());
		}
		
		return page ;
	}
	
	
	/**
	 * 修改状态
	 * @return
	 */
	@ResponseBody
	@GetMapping("/changeStatus")
    public ResponseBean changeStatus(String id){
		
		Assert.notNull(id, "主键不能为空.");
		BasicResourceEntity e = feign.getOne(id);
		log.debug("oldEntity:{} , hasStatus:{}", e, e.getHasStatus());
		log.debug("e.getHasStatus()%2:{}", e.getHasStatus() % 2);
		e.setHasStatus((e.getHasStatus() + 1) % 2);
		e = feign.save(e);
		
		return ResponseGenerator.ok(true) ; 
    }
	
}
